<template>
	<el-dialog :title="dialogTitle" :visible.sync="visible" top="0" width="560px">
		<el-form ref="form" size="medium" :model="formData" :rules="formRules" label-width="80px" style="width: 100%">
			<el-form-item label="资源类型" prop="type">
				<el-radio-group v-model="formData.type">
					<el-radio label="6" v-removeAriaHidden>视频资源</el-radio>
					<el-radio label="7" v-removeAriaHidden>文档资源</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item :label="`${labelTitle}上传`" prop="fileId">
				<el-upload v-bind="uploadConfig" :file-list="uploadList" :accept="uploadAccept">
					<el-button slot="trigger" type="primary">选择文件</el-button>
					<div class="el-upload-tips" slot="tip">{{ uploadTips }}</div>
				</el-upload>
			</el-form-item>
			<el-form-item :label="`${labelTitle}时长`" prop="strategy">
				<el-input-number v-model="formData.strategy" controls-position="right" :min="1" />
				<span class="unit">分钟</span>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" @click="handleSubmitData()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script>
import lodash from 'lodash';
import { mapGetters } from 'vuex';
import { queryKnowledge, addedKnowledge, updateKnowledge } from '@/api/course/sysKnowledge';
const baseUrl = !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl;
export default {
	props: {
		value: { type: Boolean, default: false },
		chapterId: { type: String, default: '' },
		dataId: { type: String, default: '' }
	},
	data() {
		let Authorization = this.$session.get('token');
		return {
			visible: this.value,
			formData: {},
			formRules: {
				type: [{ required: true, message: '请选择资源类型', trigger: 'change' }],
				fileId: [{ required: true, message: '请选择资源文件', trigger: 'change' }],
				strategy: [{ required: true, message: '请输入视频时长', trigger: 'blur' }]
			},
			uploadConfig: {
				limit: 1,
				ref: 'upload',
				// autoUpload: false,
				showFileList: true,
				class: 'video_upload_box',
				headers: { Authorization },
				onSuccess: this.handleUploadSuccess,
				beforeUpload: this.handleUploadBefore,
				action: `${baseUrl}/tbSysAttachment/upload`
			},
			uploadList: []
		};
	},
	computed: {
		...mapGetters(['userInfo']),
		courseId() {
			return this.$route.params.id;
		},
		addOrEdit() {
			return !this.dataId;
		},
		dialogTitle() {
			return `${this.addOrEdit ? '新增' : '修改'}资源`;
		},
		labelTitle() {
			if (this.formData.type === '6') {
				return '视频';
			} else if (this.formData.type === '7') {
				return '文档';
			} else {
				return '';
			}
		},
		uploadAccept() {
			if (this.formData.type === '6') {
				return '.mp4';
			} else if (this.formData.type === '7') {
				return '.pdf';
			}
		},
		uploadTips() {
			let accept = this.uploadAccept?.slice(1);
			return `请选择${accept}格式且大小不大于800MB的${this.labelTitle}文件`;
		},
		submitFunction() {
			return eval(this.addOrEdit ? addedKnowledge : updateKnowledge);
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			this.$nextTick(() => {
				this.initializePage(flag);
			});
		}
	},
	methods: {
		//初始化页面
		initializePage(flag) {
			if (!flag) {
				this.$refs['upload'].clearFiles();
				this.$refs['form'].resetFields();
			} else if (!this.addOrEdit) {
				this.getKnowledgeDetail();
			} else {
				this.$set(this.formData, 'type', '6');
			}
		},

		//获取知识点详情
		async getKnowledgeDetail() {
			let result = await queryKnowledge(this.dataId).then((res) => res.data);
			if (result.code === '0') {
				let datas = this.$detailData(result.data);
				let httpUrl = datas.sysAttachment?.httpUrl;
				this.formData = lodash.pick(datas, ['id', 'type', 'name', 'fileId', 'strategy', 'content']);
				this.uploadList = [{ name: datas.name, url: !httpUrl ? '' : httpUrl.replaceIP() }];
			}
		},

		//上传前
		handleUploadBefore(file) {
			let suffix = this.$getFileSuffix(file.name);
			if (['mp4'].some((n) => n === suffix)) {
				let video = document.createElement('video');
				video.src = URL.createObjectURL(file);
				video.addEventListener('loadedmetadata', () => {
					let duration = Math.round((video.duration * 100) / 60) / 100;
					this.$set(this.formData, 'strategy', duration);
				});
				this.$nextTick(() => {
					this.$refs['form'].clearValidate();
				});
			} else if (['pdf'].some((n) => n === suffix)) {
				return true;
			} else {
				this.$message.error('您选择的文件格式不正确，请重新选择文件');
				return false;
			}
		},

		handleUploadSuccess(res, file) {
			this.uploadLoading = false;
			if (res.code === '0') {
				let datas = this.$detailData(res.data);
				this.$set(this.formData, 'name', datas.oldName);
				this.$set(this.formData, 'fileId', datas.id);
				this.videoUrl = datas.httpUrl;
			}
		},

		//返回提交参数
		returnSubmitParasm() {
			let params = { ...this.formData, pid: '0' };
			let list = [{ chapterId: this.chapterId, courseId: this.courseId, type: this.formData.type }];
			params['author'] = this.userInfo.username;
			params['sysKnowledgeChapterList'] = list;
			params['sourceUnit'] = '';
			params['eduTarget'] = '';
			params['eduId'] = '';
			return params;
		},

		//提交表单
		handleSubmitData() {
			this.$refs['form'].validate((valid) => {
				if (!valid) return false;
				this.submitFormRequest();
			});
		},

		//提交表单请求
		async submitFormRequest() {
			let params = this.returnSubmitParasm();
			let result = await this.submitFunction(params).then((res) => res.data);
			if (result.code === '0') {
				this.$message.success('提交成功');
				this.$emit('refresh');
				this.visible = false;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.knowledge_container {
	flex: 1;
	padding: 1px;
}
.video_upload_box::v-deep {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	font-size: 0;
	position: relative;
	.el-upload {
		flex-shrink: 0;
		line-height: 1;
	}
	.el-upload-tips {
		flex: 1;
		font-size: 14px;
		max-height: 44px;
		line-height: 22px;
		padding-left: 12px;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		margin-top: -2px;
		overflow: hidden;
		color: #909399;
	}
	.el-upload-list {
		width: 100%;
	}
	.el-upload-list__item {
		border: solid 1px #ebeef5;
		border-top: none;
		overflow: hidden;
		.el-icon-close {
			top: 13px;
			right: 10px;
			z-index: 9;
		}
		.el-icon-close-tip {
			top: 13px;
			right: 10px;
		}
		.el-progress {
			top: 0;
			font-size: 0;
		}
		.el-progress__text {
			top: 14px;
			right: 8px;
		}
		&.is-success {
			border-top: solid 1px #ebeef5;
		}
	}
	.el-upload-list__item-name {
		position: relative;
		padding: 6px 10px;
		z-index: 2;
		overflow: hidden;
		margin-right: 28px;
		white-space: nowrap;
		text-decoration: none;
		text-overflow: ellipsis;
	}
	.el-upload-list__item-status-label {
		top: 13px;
		right: 10px;
		line-height: 1;
	}
}
</style>
